#include "PhyNetGroupParser.h"

#include "BoolParser.h"
#include "PhyNetParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

PhyNetGroupParser::PhyNetGroupParser(
    QStringParser *&_nameParser
    , BoolParser *&_optimizedParser
    , PhyNetParser *&_phyNetParser
):    m_nameParser(_nameParser)
    , m_optimizedParser(_optimizedParser)
    , m_phyNetParser(_phyNetParser)
{

}

bool PhyNetGroupParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new PhyNetGroup());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("name")))
    {
        data = reader->attributes().value(QStringLiteral("name"));
        if (!m_nameParser->parse(reader, data))
            return false;
        m_result->name = m_nameParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("name: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("optimized")))
    {
        data = reader->attributes().value(QStringLiteral("optimized"));
        if (!m_optimizedParser->parse(reader, data))
            return false;
        m_result->optimizedOptional = Optional<Bool>(m_optimizedParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("PhyNet"))
        {
            if (!m_phyNetParser->parse(reader))
                return false;
            auto result = m_phyNetParser->result();
            m_result->phyNetList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

PhyNetGroup *PhyNetGroupParser::result()
{
    return m_result.take();
}

}